package com.hibiscusking.basic.service.impl;

import com.hibiscusking.basic.config.BussinessException;
import com.hibiscusking.basic.constant.BaseConstant;
import com.hibiscusking.basic.dto.EmailVerificationDto;
import com.hibiscusking.basic.dto.PhoneSmsCodeDto;
import com.hibiscusking.basic.dto.PhoneVerificationDto;
import com.hibiscusking.basic.service.RegisterService;
import com.hibiscusking.basic.util.CheckEmailUtil;
import com.hibiscusking.basic.util.MD5Utils;
import com.hibiscusking.basic.util.PhoneFormatUtil;
import com.hibiscusking.basic.util.StrUtils;
import com.hibiscusking.user.domain.Logininfo;
import com.hibiscusking.user.domain.User;
import com.hibiscusking.user.mapper.LogininfoMapper;
import com.hibiscusking.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;
    /**
     * @date 2022/10/23 14:27
     * 手机号注册
     */
    @Override
    public void phoneRegister(PhoneSmsCodeDto phoneSmsCodeDto) {
        // 验证参数
        this.verifyParam(phoneSmsCodeDto);
        // 先添加login表
        User user = dtoConvertUser(phoneSmsCodeDto); // 把dto的值赋值给user
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo); // 把user中的属性值，赋值给logininfo
        logininfoMapper.add(logininfo); // 添加logininfo到数据库
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user); // 添加user到数据库
    }
    /**
     * @date 2022/10/23 14:27
     * 邮箱注册
     */
    @Override
    public void emailRegister(EmailVerificationDto edto) {
        // 判断参数是否正确
        this.registerEmailJudge(edto);
        // 把edto中的值赋值给user
        User user = this.edtoTurnUser(edto);
        // 把user的值赋值到logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        // 先添加logininfo
        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);
    }

    private User edtoTurnUser(EmailVerificationDto edto) {
        // 创建盐值
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = salt + edto.getPassword();

        return User.builder()
                .username(edto.getEmail())
                .email(edto.getEmail())
                .salt(salt)
                .password(pwd)
                .state(1)
                .createtime(new Date())
                .build();
    }

    private void registerEmailJudge(EmailVerificationDto edto) {

        // 判断邮箱是否正确
        if (!CheckEmailUtil.checkEmail(edto.getEmail())){
            throw new BussinessException("邮箱错误");
        }
        // 判断邮箱是否有注册
        User user = userMapper.findUserByEmail(edto.getEmail());
        if (user != null) {
            throw new BussinessException("滚去登录");
        }
        // 判断邮箱是验证码是否正确
        String emailCode = (String) redisTemplate.opsForValue().get(String.format(BaseConstant.VerfityCodeCons.SEND_VERIFICATION_EMAIL, edto.getEmail()));
        if (!edto.getEmailVerification().equals(emailCode)){
            throw new BussinessException("邮箱验证码错误");
        }
        // 判断两次密码是否正确
        if(!edto.getPassword().equals(edto.getConfirmPassword())) {
            throw new BussinessException("两次密码需要一致");
        }
    }

    private User dtoConvertUser(PhoneSmsCodeDto phoneSmsCodeDto) {
        String saltValue = StrUtils.getComplexRandomString(32); // 设置盐值
        // 把密码拼接上盐值
        String password = saltValue + phoneSmsCodeDto.getPassword();
        // 使用md5对密码进行加密
        String pwd = MD5Utils.encrypByMd5(password);
        return User.builder()
                .username(phoneSmsCodeDto.getPhone())
                .phone(phoneSmsCodeDto.getPhone())
                .salt(saltValue)
                .password(pwd)
                .createtime(new Date())
                .state(1)
                .build();
    }

    private void verifyParam(PhoneSmsCodeDto phoneSmsCodeDto) {
        // 判断手机号格式是否正确
        if (!PhoneFormatUtil.isMobileNO(phoneSmsCodeDto.getPhone())) {
            throw new BussinessException("手机号错误");
        }
        // 判断两次密码是否是一致
        if (StringUtils.isBlank(phoneSmsCodeDto.getPassword()) || !phoneSmsCodeDto.getPassword().equals(phoneSmsCodeDto.getPasswordRepeat())) {
            throw new BussinessException("两次密码需要一致,且不能为空");
        }
        // 判断两次手机号是否是一致

        // 判断短信验证码是否正确
        String phoneVerification = (String) redisTemplate.opsForValue().get(String.format(BaseConstant.VerfityCodeCons.REGISTER_SMSCODE_PHONE, phoneSmsCodeDto.getPhone()));
        if (!phoneSmsCodeDto.getSmsCode().equals(phoneVerification)) {
            throw new BussinessException("短信验证码错误");
        }
        // 判断手机号是否有注册
        User user = userMapper.findUserByPhone(phoneSmsCodeDto.getPhone());
        if (user != null) {
            throw new BussinessException("已经有注册过");
        }
    }
}
